package com.tank.nio;

import java.io.FileOutputStream;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

/**
 * Created with IntelliJ IDEA.
 * User: SuQiEr
 * Date:2017/7/30 0030
 * Time: 上午 9:15
 * To change this template use File | Settings | File Templates.
 */
public class NioTest3 {

    public static void main(String[] args) throws Exception {
        testPosition();
    }
    // position limit capacity 位置变换关系
    public static void testPosition(){
        ByteBuffer allocate = ByteBuffer.allocate(6);
        //写入4个
        for (int i = 0; i < 4; i++) {
            allocate.put((byte)i);
        }
        // position = 4 , limit =6
        allocate.flip();
        // position = 0 , limit =4
        for (int i = 0; i < 4; i++) {
            byte b = allocate.get();
            System.out.println("get:"+b);
        }
        //测试继续读取
        // position = 4 , limit =4
        allocate.flip();
        // position = 0 , limit =4
        for (int i = 0; i < 4; i++) {
            allocate.put((byte)i);
        }
        System.out.println("now buffer position = 4 , limit =4");
        allocate.put((byte) 5);
    }

    public static void testOutput() throws Exception{
        //打开流
        //获取Channel
        //定义对应类型缓冲及长度
        //数据写入缓冲
        //缓冲反转
        //缓冲写入管道
        //关闭流

        FileOutputStream fileOutputStream = new FileOutputStream("NioTest3.txt");

        FileChannel channel = fileOutputStream.getChannel();

        ByteBuffer buffer = ByteBuffer.allocate(10);

        byte[] message = "abcdefghij".getBytes();

        for (byte b:message) {
            buffer.put(b);
        }

        buffer.flip();

        channel.write(buffer);

        fileOutputStream.close();
    }


}
